package com.example.tutorialmongodb.syncdata.service;

import com.example.tutorialmongodb.syncdata.mapper.SyncDataMapper;
import com.example.tutorialmongodb.syncdata.model.UserLoginPromotionChannelEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: cph
 * @date: 2021/11/11 14:14
 */
@Slf4j
@Component
public class SyncDataService implements InitializingBean {

    @Resource
    private MongoDBService mongoDBService;
    @Resource
    private SyncDataMapper syncDataMapper;

    @Override
    public void afterPropertiesSet() {
        int count = 0;
        try {
            List<UserLoginPromotionChannelEntity> list = syncDataMapper.findList();
            log.info("online mysql2mongo original size:[{}]", list.size());
            for (UserLoginPromotionChannelEntity t : list) {
                long start = System.currentTimeMillis();
                log.info(
                        "online mysql2mongo userId:[{}], tuiguangId:[{}], generalizeId:[{}], url:[{}], updateTime:[{}]",
                        t.getUserId(),
                        t.getTuiguangId(),
                        t.getGeneralizeId(),
                        t.getUrl(),
                        t.getUpdateTime());
                mongoDBService.upsert(
                        t.getUserId(),
                        t.getTuiguangId(),
                        t.getGeneralizeId(),
                        t.getUrl(),
                        t.getUpdateTime());
                count++;
                long end = System.currentTimeMillis();
                log.info("online mysql2mongo single cost:[{}]s", (end - start) / 1000L);
            }
            log.info("online mysql2mongo sync size:[{}]", count);
        } catch (Exception e) {
            log.info("online mysql2mongo sync size:[{}]", count);
            log.info("mysql2mongo同步异常", e);
        }
    }
}
